package com.cjst.controller.part;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.part.PartType;
import com.cjst.pojo.part.Parts;
import com.cjst.pojo.part.PtypeRelevance;
import com.cjst.pojo.sys.SysOffice;
import com.cjst.pojo.sys.SysUser;
import com.cjst.sdp.util.MapUtils;
import com.cjst.service.part.PartTypeService;
import com.cjst.service.part.PartsService;
import com.cjst.service.part.PtypeRelevanceService;
import com.cjst.service.sys.SysDictService;
import com.cjst.service.sys.SysOfficeService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.CloneClass;
import com.cjst.util.UserPrincipalUtil;
import com.cjst.util.code.PageUtil;
import com.cjst.util.common.DateUtil;
import com.cjst.util.json.ResultObj;

@Controller
@RequestMapping("/part/parts")
public class PartsController extends BaseController{
	private static final Logger log = Logger.getLogger(PartsController.class);
	@Value("${file.path}")
    private String filePath;
	@Autowired
	private PartsService partsService;
	
	@Autowired
	private PtypeRelevanceService ptypeRelevanceService;
	
	@Autowired
	private PartTypeService partTypeService;
	
	@Autowired
	private SysOfficeService sysOfficeService;
	@Autowired
	private SysDictService dictService;
	
	@RequestMapping(value = "", method = RequestMethod.GET)
    //@RequiresPermissions("parts")
    public String toParts() {
        return "part/parts/parts";
    }
	
	/**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @RequiresPermissions("parts_add")
    public String addPartsr(Model model) {
    	WherePrams prams=Method.where("status", C.EQ, "1");
    	prams.and("type", C.EQ, 0);
    	List<SysOffice> officeList=sysOfficeService.list(prams);
    	WherePrams typePrams=Method.where("delFlag", C.EQ, 0);
    	//typePrams.and("type", C.EQ, 0);
    	List<PartType> partTypeList=partTypeService.list(typePrams);
    	List<Map<String, String>>  mindTypes= dictService.getDicts("mind_type");
		if(mindTypes!=null&&mindTypes.size()>0) {
			model.addAttribute("mindTypes", mindTypes);
		}
    	model.addAttribute("officeList", officeList);
    	model.addAttribute("partTypeList", partTypeList);
        return "part/parts/parts_add";
    }
	
	
	@RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Parts parts) {
		/*
		if(StringUtils.isEmpty(parts.getPtypeParent())){
			return new ResultObj(1, "参数传递错误，查询失败", null);
		}
		
		WherePrams wherePrams = Method.where("delFlag", C.EQ, "0");
		
		wherePrams=wherePrams.and("ptypeParent", C.EQ, parts.getPtypeParent());
		List<Parts> result=partsService.list(wherePrams);
		*/
		return null;
	}
	
	
	@RequestMapping(value = "/listAll")
	@ResponseBody
	public Object list() {
		
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		WherePrams wherePrams = Method.where("delFlag", C.EQ, "0");
		
		/*
		 * 增加权限过滤
		 */
		UserPrincipalUtil.getPriceMegod(wherePrams, sysUser, null);
		
		PageUtil<Parts> pageUtil = partsService.listPageCount(wherePrams);
        List<Parts> partss = pageUtil.getData();
		
        List<Map<String, Object>> maps = new ArrayList<>();
        for (Parts parts : partss) {
            Map<String, Object> partsMap = MapUtils.transBean2Map(parts);
            maps.add(partsMap);
        }
        
        
        
        PageUtil<Map<String, Object>> pages = new PageUtil<>();

        CloneClass.getClone(pageUtil, pages);
        pages.setData(maps);
        return this.packForBT(pages);
	}
	
	
	@RequestMapping(value = "/save/addOne", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("parts_add")
    public Object addOne(Parts parts, HttpServletRequest req) {
//		if (StringUtils.isEmpty(parts.getPartNo())) {
//			return new ResultObj(1, "参数传递错误，父类id不能为空 ,失败", null);
//		}
		
		//
		
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		parts.setCreateBy(sysUser.getId());
		parts.setCreateTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
		String flag=partsService.addLocalByid(parts);
		/*String fback2=parts.getFback2();
		PtypeRelevance pr=new PtypeRelevance();
		pr.setCreatedBy(sysUser.getId());
		pr.setDelFlag(0);
		pr.setPartId(flag);
		pr.setTypeId(fback2);
		ptypeRelevanceService.addLocalByid(pr);*/
		
		
		return new ResultObj(0, "保存成功", flag);
	}
	
	 /**
     * 部件类型详情
     * @param partsId
     * @param model
     * @return
     */
    @RequestMapping(value = "/view/{partsId}", method = RequestMethod.GET)
    @RequiresPermissions("parts_view")
    public String viewUser(@PathVariable String partsId, Model model) {
        WherePrams where = Method.where("id", C.EQ, partsId);
        Parts parts = partsService.get(where);
        if (parts != null) {
            Map<String, Object> partsMap = MapUtils.transBean2Map(parts);
            model.addAttribute("parts", partsMap);
        }
        return "part/parts/parts_detail";
    }

	
	@RequestMapping(value = "/save/addMany")
    @ResponseBody
    public Object addMany(Parts parts) {
		
		
		return null;
	}
	
	@RequestMapping(value = "/delete/deleteOne")
    @ResponseBody
    public Object deleteOne(Parts parts) {
		
		
		return null;
	}
	
	@RequestMapping(value = "/save/delete")
    @ResponseBody
    @RequiresPermissions("parts_delete")
    public Object saveDelete(String ids) {
		 if (!StringUtils.isNotEmpty(ids)) {
	            return new ResultObj(1, "参数传递错误", null);
	        }
	        String[] list = ids.split(",");
	        for (String id : list) {
	            //Parts parts2 = partsService.get(id);
	            WherePrams wherePrams = Method.where("id", C.EQ, id);
	            Parts parts1 = new Parts();
	            parts1.setDelFlag(1);
	            partsService.updateLocal(parts1, wherePrams);
	            
	            /*
	             * 同时删除RELEVANCE
	             */
	            
	            
	        }

	        return new ResultObj(0, "删除成功", null);
	}
	
	
	@RequestMapping(value = "/update/{partsId}", method = RequestMethod.GET)
	@RequiresPermissions("parts_update")
	public Object toUpdate(@PathVariable String partsId, Model model) {
		WherePrams prams=Method.where("status", C.EQ, "1");
    	prams.and("type", C.EQ, 0);
    	List<SysOffice> officeList=sysOfficeService.list(prams);
    	WherePrams typePrams=Method.where("delFlag", C.EQ, 0);
    	//typePrams.and("type", C.EQ, 0);
    	List<PartType> partTypeList=partTypeService.list(typePrams);
    	List<Map<String, String>>  mindTypes= dictService.getDicts("mind_type");
		if(mindTypes!=null&&mindTypes.size()>0) { 
			model.addAttribute("mindTypes", mindTypes);
		}
    	model.addAttribute("officeList", officeList);
    	model.addAttribute("partTypeList", partTypeList);
		WherePrams where = Method.where("id", C.EQ, partsId);
		Parts parts = partsService.get(where);

		if (parts != null) {
			//Map<String, Object> userMap = MapUtils.transBean2Map(parts);
			if(parts.getFback1()!=null && parts.getFback1().length()>0){
				parts.setFback1(filePath+parts.getFback1());
			}
			model.addAttribute("parts", parts);

		}

		return "part/parts/parts_edit";
	}
	
	
	@RequestMapping(value = "/save/updateOne", method = RequestMethod.POST)
    @ResponseBody
    public Object updateOne(Parts parts) {
		if (parts == null) {
            return new ResultObj(1, "参数传递错误，修改失败", null);
        }
        WherePrams where = Method.where("id", C.EQ, parts.getId());
        Parts parts2 = partsService.get(where);
        if (parts2 == null) {
            return new ResultObj(1, "根据Id未查询到部件信息，修改失败", null);
        }
      
        /*
         * 
         * 往后需添加一系列修改规则
         * 
         */
        
        
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		parts.setUpdateBy(sysUser.getId());

        int flag = partsService.updateLocal(parts);
        //updateRedisUser();
        return new ResultObj(0, "修改成功", flag);
	}
	

}
